/**
 * 全局消息管理器
 * 负责WebSocket连接管理和消息传递
 */
class MessageManager {
	constructor() {
		this.ws = null
		this.wsConnected = false
		this.reconnectTimer = null
		this.messageListeners = new Map()
		this.friendList = []
		this.currentChatUser = null
		// this.wsUrl = 'wss://kaoshi.apiwww.cn:8283'
		this.wsUrl = 'wss://xcxgl.yyjycn.com:8283'
		this.clientId = null
		this.userId = null
	}

	// 初始化WebSocket连接
	initWebSocket() {
		if (this.ws) {
			this.closeWebSocket()
		}

		this.ws = uni.connectSocket({
			url: this.wsUrl,
			success: () => {
				console.log('WebSocket connecting...')
			},
			fail: (err) => {
				console.error('WebSocket connect error:', err)
			}
		})

		// 监听WebSocket事件
		uni.onSocketOpen(() => {
			this.wsConnected = true
			console.log('WebSocket 已连接')
			// 设置全局状态
			getApp().globalData = getApp().globalData || {}
			getApp().globalData.wsConnected = true
			getApp().globalData.ws = this.ws
		})

		uni.onSocketMessage((res) => {
			this.handleSocketMessage(res)
		})

		uni.onSocketClose(() => {
			this.wsConnected = false
			getApp().globalData.wsConnected = false
			console.log('WebSocket 已断开')
			// 自动重连
			this.reconnectTimer = setTimeout(() => {
				this.initWebSocket()
			}, 3000)
		})

		uni.onSocketError((err) => {
			this.wsConnected = false
			getApp().globalData.wsConnected = false
			console.error('WebSocket 错误:', err)
		})
	}

	// 处理WebSocket消息
	handleSocketMessage(res) {
		let msgObj
		try {
			msgObj = JSON.parse(res.data)
		} catch (e) {
			msgObj = { content: res.data }
		}
		console.log('收到消息:', res.data,msgObj)

		if (msgObj.type == "init") {
			this.clientId = msgObj.client_id
			// client_id 赋值后再触发 wsInited 事件
			uni.$emit('wsInited');
		} else if (msgObj.type == "chatMessage") {
			console.log('message-jieshou',msgObj.data.id,this.userId);
			if (msgObj.data.id == this.userId) {
				const message = {
					content: msgObj.data.content[0].data,
					userType:'friend',
					timestamp: Date.now(),
					type:'text'
				}
	
	
				console.log('message-jieshou-wy',message);
				// 更新好友列表
				this.updateFriendLastMessage(message)
				// 触发消息事件
				this.emitMessage(message)
			}
			
		}
	}

	// 关闭WebSocket连接
	closeWebSocket() {
		if (this.wsConnected) {
			uni.closeSocket()
		}
		this.ws = null
		this.wsConnected = false
		getApp().globalData.wsConnected = false
		if (this.reconnectTimer) {
			clearTimeout(this.reconnectTimer)
			this.reconnectTimer = null
		}
	}

	// 发送消息
	sendMessage(message) {
		if (this.wsConnected && this.ws) {
			uni.sendSocketMessage({
				data: JSON.stringify(message),
				success: () => {
					console.log('消息已通过 WebSocket 发送')
				},
				fail: (err) => {
					console.error('WebSocket 发送失败', err)
				}
			})
		} else {
			uni.showToast({ title: '网络连接异常', icon: 'none' })
		}
	}

	// 更新好友最后消息
	updateFriendLastMessage(message) {
		const friendIndex = this.friendList.findIndex(user => user.id === message.from)
		if (friendIndex !== -1) {
			this.friendList[friendIndex].lastMessage = message.content
			this.friendList[friendIndex].lastTime = this.formatTime(new Date(message.timestamp))
	
			// 如果当前不在该好友的聊天页面，增加未读数
			if (this.currentChatUser !== message.from) {
				this.friendList[friendIndex].unreadCount = (this.friendList[friendIndex].unreadCount || 0) + 1
			}
		}
	}

	// 设置好友列表
	setFriendList(friendList) {
		this.friendList = friendList
	}
	setUserId(userId) {
		this.userId = userId;
	}

	// 获取好友列表
	getFriendList() {
		return this.friendList
	}

	// 进入聊天
	enterChat(userId) {
		this.currentChatUser = userId
		// 清除该用户的未读消息
		const friendIndex = this.friendList.findIndex(user => user.id === userId)
		if (friendIndex !== -1) {
			this.friendList[friendIndex].unreadCount = 0
		}
	}

	// 离开聊天
	leaveChat() {
		this.currentChatUser = null
	}

	// 添加消息监听器
	addMessageListener(userId, callback) {
		if (!this.messageListeners.has(userId)) {
			this.messageListeners.set(userId, [])
		}
		this.messageListeners.get(userId).push(callback)
	}

	// 移除消息监听器
	removeMessageListener(userId, callback) {
		if (this.messageListeners.has(userId)) {
			const listeners = this.messageListeners.get(userId)
			const index = listeners.indexOf(callback)
			if (index > -1) {
				listeners.splice(index, 1)
			}
		}
	}

	// 触发消息事件
	emitMessage(message) {
		// 触发全局事件
		uni.$emit('newMessage', message)

		// 触发特定用户的监听器
		if (this.messageListeners.has(message.from)) {
			const listeners = this.messageListeners.get(message.from)
			listeners.forEach(callback => {
				callback(message)
			})
		}
	}

	// 格式化时间
	formatTime(date = new Date(), format = 'HH:MM') {
		const hours = date.getHours().toString().padStart(2, '0')
		const minutes = date.getMinutes().toString().padStart(2, '0')
		return format.replace('HH', hours).replace('MM', minutes)
	}

	// 获取连接状态
	isConnected() {
		return this.wsConnected
	}

	// 获取client_id的方法
	getClientId() {
		return this.clientId;
	}
}

// 创建全局实例
const messageManager = new MessageManager()

// 导出实例
export default messageManager 